package com.example.toolproject.demo.service.serviceimpl;

import com.alibaba.fastjson.JSONObject;
import com.example.toolproject.demo.domain.DataSearch;
import com.example.toolproject.demo.domain.ImportMessage;
import com.example.toolproject.demo.domain.User;
import com.example.toolproject.demo.mapper.DataSearchMapper;
import com.example.toolproject.demo.mapper.UserDataSearchMapper;
import com.example.toolproject.demo.service.DataSearchService;
import com.example.toolproject.demo.util.ResultBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DataSearchServiceImpl
 * @Description TODO
 * @Author lvyongwei
 * @Date 2020-06-19 13:52
 **/
@Service
public class DataSearchServiceImpl implements DataSearchService {

    @Autowired
    private DataSearchMapper dataSearchMapper;

    @Autowired
    private UserDataSearchMapper userDataSearchMapper;

    private Logger logger= LoggerFactory.getLogger(DataSearchServiceImpl.class);

    /**
     * 添加数据信息
     * @param dataSearch
     * @return
     */
    @Override
    public boolean insertData(DataSearch dataSearch) {
        return dataSearchMapper.insertData(dataSearch);
    }

    /**
     * 导入数据
     * @param dataSearchs  数据集合
     * @return
     */
    @Override
    public ResultBean imports(List<Object> dataSearchs , User user) {
        //记录导入失败条数
        int failCount=0;
        //记录导入成功条数
        int successCount=0;
        //记录导入失败信息集合
        List<ImportMessage> failList=new ArrayList<ImportMessage>();
        List<ImportMessage> successList=new ArrayList<ImportMessage>();
        //遍历数据信息
        for(Object dataSearch:dataSearchs){
            DataSearch dataSearch1= (DataSearch) dataSearch;
            /**
             * 设置用户id和角色id
             */
            dataSearch1.setUserId(user.getId());
            dataSearch1.setRoleId(user.getRoleId());
            //根据遍历数据查看标题名  是否重复
            logger.error(dataSearch1.getName());
            DataSearch flag=dataSearchMapper.selectDataSearch(dataSearch1.getName());
            if(flag!=null){
                //创建记录错误信息对象
                ImportMessage importMessage=new ImportMessage();
                importMessage.setDataSearch(dataSearch1);
                importMessage.setImportErrorMessage("标题名重复");
                failList.add(importMessage);
                //失败条数+1
                failCount++;
            }else if(dataSearch1.getType()==0) {
                //创建记录错误信息对象
                ImportMessage importMessage=new ImportMessage();
                importMessage.setDataSearch(dataSearch1);
                importMessage.setImportErrorMessage("类别不存在，请输入正确的类别");
                failList.add(importMessage);
                failCount++;
            }else{
                try{
                    dataSearchMapper.insertData(dataSearch1);
                    ImportMessage importMessage=new ImportMessage();
                    importMessage.setDataSearch(dataSearch1);
                    importMessage.setImportErrorMessage("导入成功");
                    successList.add(importMessage);
                    successCount++;
                }catch(Exception e){
                    failCount++;
                    logger.error("导入失败");
                }
            }
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("failData",failList);
        jsonObject.put("successData",successList);
        return ResultBean.success("一共"+dataSearchs.size()+"条数据，导入成功"+successCount+"条,"+"导入失败"+failCount+"条。",jsonObject);
    }


    /**
     * 根据标题类型查找数据
     * @param type 类型
     * @return
     */
    @Override
    public List<DataSearch> selectAllDataSearch(int type, int userId) {
        return dataSearchMapper.selectAllDataSearch(type,userId);
    }

    /**
     * 根据type  以及搜索条件模糊查询  所有数据
     * @param type     类型
     * @param message  搜索条件
     * @return
     */
    @Override
    public List<DataSearch> selectAllDataSearchByMessage(int type, String message, int userId) {
        return dataSearchMapper.selectAllDataSearchByMessage(type,message,userId);
    }

    /**
     * 根据数据id查询详情信息
     * @param dataSearchId  数据信息id
     * @return
     */
    @Override
    public DataSearch getDataSearchById(int dataSearchId) {
        return dataSearchMapper.getDataSearchById(dataSearchId);
    }

    /**
     * 获取到自己引用的所有的数据资源
     * @return
     */
    @Override
    public List<DataSearch> getSelfAllDataSearch(int userId) {
        return dataSearchMapper.getSelfAllDataSearch(userId);
    }

    /**
     * 根据类型获取简介，名称数据
     * @param type
     * @return
     */
    @Override
    public List<String> getDataSearch(int type) {
        return dataSearchMapper.getDataSearch(type);
    }

    /**
     * 根据引用数据及分类，获取要分词的数据信息
     * @param userId
     * @param type
     * @return
     */
    @Override
    public List<String> getDataSearch2(int userId, int type) {
        return dataSearchMapper.getDataSearch2(userId,type);
    }


    /**
     * 删除学生以及游客身份的人导入的内容信息
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean deleteDataSearch(User user) {
        if(StringUtils.isEmpty(user.getRoleId()) || user.getId()!=0){
            try{
                List<Long> ids = dataSearchMapper.getDataSearchIds2();
                if(ids.size()==0){
                    return ResultBean.success("退出成功，同时删除导入文化资源信息");
                }
                userDataSearchMapper.deleteUserDataSearch(ids);
                dataSearchMapper.deleteDataSearch(ids);
                return ResultBean.success("退出成功，同时删除导入文化资源信息");
            }catch (Exception e){
                /**
                 * 删除失败，但是也退出
                 */
                logger.error("用户id："+user.getId()+"角色是："+user.getRoleId()+"的用户导入的文化资源数据删除失败");
                return ResultBean.success("退出成功");
            }
        }
        int roleId=user.getRoleId();
        /**
         * 判断roleId是否是学生或游客
         */
        if(roleId !=1 || roleId!=2){
            /**
             * 获取导入的数据id
             */
            try{
                List<Long> ids = dataSearchMapper.getDataSearchIds(roleId,user.getId());
                if(ids.size()==0){
                    return ResultBean.success("退出成功，同时删除导入文化资源信息");
                }
                userDataSearchMapper.deleteUserDataSearch(ids);
                dataSearchMapper.deleteDataSearch(ids);
                return ResultBean.success("退出成功，同时删除导入文化资源信息");
            }catch (Exception e){
                /**
                 * 删除失败，但是也退出
                 */
                logger.error("用户id："+user.getId()+"角色是："+user.getRoleId()+"的用户导入的文化资源数据删除失败");
                return ResultBean.success("退出成功");
            }
        }
        return ResultBean.success("退出成功");
    }

}
